package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.mapper.ApUnlikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnLikesBehaviorService;
import com.heima.model.behavior.dto.UnLikesBehaviorDto;
import com.heima.model.behavior.pojo.ApBehaviorEntry;
import com.heima.model.behavior.pojo.ApLikesBehavior;
import com.heima.model.behavior.pojo.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojo.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author TheCai
 * @date 2021/6/5 9:27
 */
@Service
public class ApUnLikesBehaviorServiceImpl
    extends ServiceImpl<ApUnlikesBehaviorMapper, ApUnlikesBehavior>
    implements ApUnLikesBehaviorService {

  @Autowired ApBehaviorEntryService apBehaviorEntryService;

  @Override
  public ResponseResult unLike(UnLikesBehaviorDto dto) {
    // 检查参数
    if (dto.getArticleId() == null || dto.getEquipmentId() == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
    ApUser user = AppThreadLocalUtils.getUser();
    if (user == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
    }
    // 找到实体
    ApBehaviorEntry apBehaviorEntry =
        apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
    if (apBehaviorEntry == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
    // 找到不喜欢行为,看看有没有
    if (dto.getType().intValue() == 0) {

      ApUnlikesBehavior apUnLikesBehavior =
          this.getOne(
              Wrappers.<ApUnlikesBehavior>lambdaQuery()
                  .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId())
                  .eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId()));

      if (apUnLikesBehavior != null) {
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "请勿重复操作");
      }
      // 保存不喜欢
      apUnLikesBehavior = new ApUnlikesBehavior();
      apUnLikesBehavior.setEntryId(apBehaviorEntry.getId());
      apUnLikesBehavior.setArticleId(dto.getArticleId());
      apUnLikesBehavior.setType(dto.getType());
      apUnLikesBehavior.setCreatedTime(new Date());

      this.save(apUnLikesBehavior);

    } else {
      // 如果有再点一下直接删除
      this.remove(
          Wrappers.<ApUnlikesBehavior>lambdaQuery()
              .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId())
              .eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId()));
    }

    return ResponseResult.okResult();
  }
}
